
package com.y.fund.utils;

import java.time.LocalDateTime;
import java.util.concurrent.ThreadLocalRandom;


public class IdGenerator {

	private static final int SvrSerial = 1000 + ThreadLocalRandom.current().nextInt(8999);

	private static final int INIT_INCREMENT = 1000000;
	
	private static final int MAX_INCREMENT = 9999966;
	
	private static volatile int adder = INIT_INCREMENT + ThreadLocalRandom.current().nextInt(1000);
	
	private static int increment(){
		synchronized ("idgenerator.inc") {
			if((++adder) > MAX_INCREMENT){
				adder = INIT_INCREMENT + ThreadLocalRandom.current().nextInt(1000);
			}
			return adder;
		}
	}

	/** Generate a 32-bit string of all numbers */
	public static String Id32(){
		StringBuilder idStr = new StringBuilder(32);
		LocalDateTime lt = LocalDateTime.now();
		
		idStr.append(lt.getYear());
		if(lt.getMonthValue()<10){
			idStr.append("0");
		}
		idStr.append(lt.getMonthValue());
		
		if(lt.getDayOfMonth()<10){
			idStr.append("0");
		}
		idStr.append(lt.getDayOfMonth());
		
		if(lt.getHour()<10){
			idStr.append("0");
		}
		idStr.append(lt.getHour());
		if(lt.getMinute()<10){
			idStr.append("0");
		}
		idStr.append(lt.getMinute());
		if(lt.getSecond()<10){
			idStr.append("0");
		}
		idStr.append(lt.getSecond());
		
		idStr.append(SvrSerial).append(increment())
			.append(ThreadLocalRandom.current().nextInt(100,999))
			.append(ThreadLocalRandom.current().nextInt(100,999))
			.append(ThreadLocalRandom.current().nextInt(10));
		return idStr.toString();
	}


	/** Generate a random number excluding month, year and day, with a length of 26 bits */
	public static String Id26WithoutYearMonthDay(){
		StringBuilder idStr = new StringBuilder(26);
		LocalDateTime lt = LocalDateTime.now();
		idStr.append(SvrSerial);
		if(lt.getHour()<10){
			idStr.append("0");
		}
		idStr.append(lt.getHour());
		if(lt.getMinute()<10){
			idStr.append("0");
		}
		idStr.append(lt.getMinute());
		if(lt.getSecond()<10){
			idStr.append("0");
		}

		idStr.append(lt.getSecond());
		idStr.append(ThreadLocalRandom.current().nextInt(10,99));
		idStr.append(increment())
			.append(ThreadLocalRandom.current().nextInt(100,999))
			.append(ThreadLocalRandom.current().nextInt(100,999))
			.append(ThreadLocalRandom.current().nextInt(10));
		return idStr.toString();
	}

}
